using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Xml;
using Graffiti.Core;
using System.Web;

namespace Graffiti.Slide.Show
{
    /// <summary>
    /// Slide.Show Photo Gallery
    /// </summary>
    public class FileSystemSlideShow2Plugin : BaseSlideShowPlugin
    {

        #region Properties

        private bool _createThumbnails = true;
        public bool CreateThumbnails
        {
            get { return _createThumbnails; }
            set { _createThumbnails = value; }
        }

        private string _photoDataLocation = string.Empty;
        public string PhotoDataLocation
        {
            get { return _photoDataLocation; }
            set { _photoDataLocation = value; }
        }

        private string _dataFileUrl = string.Empty;
        public string DataFileUrl
        {
            get { return _dataFileUrl; }
            set { _dataFileUrl = value; }
        }

        private int _startAlbum = -1;
        public int StartAlbum
        {
            get { return _startAlbum; }
            set { _startAlbum = value; }
        }

        private string _slideTransition = "CrossFadeTransition";
        public string SlideTransition
        {
            get { return _slideTransition; }
            set { _slideTransition = value; }
        }

        #endregion

        #region Constructor
        public FileSystemSlideShow2Plugin()
        {

        }
        #endregion

        #region GraffitiEvent Properties

        public override string Name
        {
            get { return "Slide.Show2 Photo Gallery Plugin"; }
        }

        public override string Description
        {
            get
            {
                return "Adds a photo gallery to a post page using the Slide.Show2 Silverlight component.";
            }
        }

        #endregion

        #region Events

        protected override void ga_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            HttpContext context = app.Context;
            string path = context.Request.Path.ToLower();

            if (path.Contains("/slideshowplugin-fs-config.aspx"))
            {
                HandleConfigRequest(context);
                return;
            }
            else if (path.Contains("/slideshowplugin-fs-data.aspx"))
            {
                FolderDataHandler folderData = new FolderDataHandler(context, PhotoDataLocation, StartAlbum, SlideTransition);
                folderData.ProcessRequest();
                return;
            }
        }

        protected override void ga_RenderPostBody(StringBuilder sb, PostEventArgs e)
        {
            if (e.RenderLocation == PostRenderLocation.Web && e.Post.Name.ToLower() == PostName.ToLower())
            {
                Macros macros = new Macros();

                sb.AppendFormat("\n<object type=\"application/x-silverlight-2\" data=\"data:application/x-silverlight-2,\" width=\"{0}\" height=\"{1}\">\n", this.Width, this.Height);
                sb.AppendFormat("<param name=\"background\" value=\"{0}\" />\n", this.BackgroundColor);

                if (this.Theme == "XML")
                    sb.AppendFormat("<param name=\"initParams\" value=\"ConfigurationProvider=XmlConfigurationProvider;Path={0},DataProvider=XmlDataProvider;Path={1}\" />\n", VirtualPathUtility.ToAbsolute("~/slideshowplugin-fs-config.aspx"), VirtualPathUtility.ToAbsolute("~/slideshowplugin-fs-data.aspx"));
                else
                    sb.AppendFormat("<param name=\"initParams\" value=\"ConfigurationProvider={0},DataProvider=XmlDataProvider;Path={1}\" />\n", this.Theme, VirtualPathUtility.ToAbsolute("~/slideshowplugin-fs-data.aspx"));

                sb.AppendFormat("<param name=\"source\" value=\"{0}\" />\n", macros.FullUrl(VirtualPathUtility.ToAbsolute("~/Vertigo.SlideShow.xap")));
                sb.Append(_resDownloadSilverlight);
                sb.Append("</object>\n");
            }
        }

        #endregion

        #region Configuration

        protected override FormElementCollection AddFormElements()
        {
            FormElementCollection fec = new FormElementCollection();
            fec.Add(new MessageElement("intro", "<strong>Slide.Show Photo Gallery</strong>",
                "<a href=\"http://kevinharder.com/downloads/graffiti/slide-show-plugin/\">Click here</a> for more help &amp; info."));

            fec.Add(new MessageElement("photoLocationHeader", "<strong>Setup Instructions</strong><br />Create a new folder inside your site to be the photo gallery root. Inside of it, create subfolders for each album that you want. Put the image files in the album folders. If you want album descriptions, create a plain text file called album.txt inside each album folder that contains that album's description.", null));
            fec.Add(new TextFormElement("photoDataLocation", "Location of photo gallery folder", "Enter the path to the photo gallery root (the folder that contains your albums). It can be absolute (c:\\website\\photos) or relative starting with a tilde (~/photos)."));
            
            // Thumbnail support removed, Slide.Show doesn't seem to be working well with thumbnails
            // fec.Add(new CheckFormElement("createThumbnails", "Create thumbnail images", "This plugin will look for thumbnail versions of the images in a <i>thumbnails</i> subfolder of each album. If checked, thumbnails will be created automatically if they don't already exist.", true));

            AddBaseFormElements(fec);

            fec.Add(new MessageElement("advancedOptions", "<br /><strong>Advanced Options</strong>", "Below are advanced optional settings if you want greater control over how the gallery is rendered."));
            ListFormElement lfe = new ListFormElement("slideTransition", "Transition Effect", "Select the type of transition effect to use between photos");
            lfe.Add(new ListItemFormElement("Cross Fade", "CrossFadeTransition", true));
            lfe.Add(new ListItemFormElement("Circle In", "CircleInTransition"));
            lfe.Add(new ListItemFormElement("Circle Out", "CircleOutTransition"));
            lfe.Add(new ListItemFormElement("Slide Left", "SlideLeftTransition"));
            lfe.Add(new ListItemFormElement("Slide Right", "SlideRightTransition"));
            lfe.Add(new ListItemFormElement("Slide Down", "SlideDownTransition"));
            lfe.Add(new ListItemFormElement("Slide Up", "SlideUpTransition"));
            lfe.Add(new ListItemFormElement("None", "NoTransition"));
            fec.Add(lfe);

            fec.Add(new TextFormElement("startAlbum", "Album Number to Auto Start", "The first album found will automatically start playing. To start a different one, enter the number below (starting with 0)."));
            fec.Add(new TextFormElement("dataFileUrl", "Custom XML Data File URL", "You can create your own data.xml file that contains albums, image file paths, and descriptions. Enter the full URL to the data.xml file here. It will be used instead of looking in the folder location above."));

            AddAboutFormElements(fec);

           return fec;
        }

        protected override NameValueCollection DataAsNameValueCollection()
        {
            NameValueCollection nvc = new NameValueCollection();
            nvc["photoDataLocation"] = PhotoDataLocation;
            nvc["dataFileUrl"] = DataFileUrl;
            nvc["slideTransition"] = SlideTransition;
            //nvc["createThumbnails"] = CreateThumbnails.ToString();

            if (StartAlbum < 0)
                nvc["startAlbum"] = string.Empty;
            else
                nvc["startAlbum"] = StartAlbum.ToString();

            AddBaseConfigValues(nvc);
            
            return nvc;
        }

        public override StatusType SetValues(System.Web.HttpContext context, NameValueCollection nvc)
        {
            if (string.IsNullOrEmpty(nvc["photoDataLocation"]) && string.IsNullOrEmpty(nvc["dataFileUrl"]))
            {
                SetMessage(context, "You forgot to enter the path to the photo gallery folder.");
                return StatusType.Error;
            }
            if (!string.IsNullOrEmpty(nvc["photoDataLocation"]) && !string.IsNullOrEmpty(nvc["dataFileUrl"]))
            {
                SetMessage(context, "You entered both a photo gallery folder path and a XML Data File Url! Please use one or the other. ");
                return StatusType.Error;
            }
            PhotoDataLocation = nvc["photoDataLocation"];
            DataFileUrl = nvc["dataFileUrl"];
            SlideTransition = nvc["slideTransition"];
            //CreateThumbnails = ConvertStringToBool(nvc["createThumbnails"]);

            try
            {
                if (!string.IsNullOrEmpty(nvc["startAlbum"]))
                    StartAlbum = int.Parse(nvc["startAlbum"]);
                else
                    StartAlbum = -1;
            }
            catch
            {
                StartAlbum = -1;
            }

            return SetBaseValues(context, nvc);
        }

        #endregion

    }
}
